<template>
  <div>
    <el-row :span="4">
      <!--&lt;!&ndash;  用户搜索框&ndash;&gt;-->
      <div v-if="topInputShow">
      <el-form :inline="true" class="demo-form-inline" align="left">
        <el-form-item label="楼栋/单元">
          <el-cascader
              style="float: left"
              v-model="BuildingList"
              :options="roomTree"
              clearable
              @change="selectUnitAndBuilding"></el-cascader>
        </el-form-item>
        <el-form-item label="房屋状态">
          <el-select v-model="roomStatus" clearable placeholder="请选择">
            <el-option
                v-for="item in dictStatus"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="loadRoomList" style="background-color: #23C6C8" icon="el-icon-search">查询
          </el-button>
          <el-button icon="el-icon-refresh" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
      </div>

      <!--    新增--;修改--删除--导入--;导出-->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="onRoomAdd">新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single"
                     @click="onUpdateRoom">修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="BatchTips">
            删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" icon="el-icon-download" size="mini" @click="outExport">导出</el-button>
        </el-col>
      </el-row>
      <el-row class="btn-circle" style="float: right">
        <el-button icon="el-icon-search" size="mini" circle @click="topInputShows"></el-button>
        <el-button icon="el-icon-refresh" size="mini" circle @click="refresh"></el-button>
      </el-row>

      <!--  用户数据列表-->
      <el-table :data="rooms"
                :header-row-style="{height:'50px'}"
                id="userData"
                :header-cell-style="{background:'#f5f7fa',padding:'0px'}"
                :row-style="{height:'5px'}"
                :cell-style="{padding:'0px'}"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center"/>
        <el-table-column
            label="序号"
            type="index"
            width="150"
            align="center">
        </el-table-column>
        <el-table-column label="小区名称" align="center" prop="community.communityName"/>
        <el-table-column label="楼栋名称" align="center" prop="building.buildingName"/>
        <el-table-column label="单元名称" align="center" prop="unit.unitName"/>
        <el-table-column label="楼层" align="center" prop="roomLevel"/>
        <el-table-column label="房间编号" align="center" prop="roomCode"/>
        <el-table-column label="房间名称" align="center" prop="roomName"/>
        <el-table-column label="房屋建筑面积" align="center" prop="roomAcreage"/>
        <el-table-column label="算费系数" align="center" prop="roomCost"/>
        <el-table-column label="房屋状态" align="center" prop="roomStatus" width="160">
          <template slot-scope="scope" >
            <template v-for="item in dictStatus" v-if="item.dictValue==scope.row.roomStatus" >{{item.dictLabel}}</template>
          </template>
        </el-table-column>
        <el-table-column label="是否商铺" align="center" prop="roomIsShop">
          <template slot-scope="scope">
            <template v-for="item in dictYesNo" v-if="item.dictValue ==scope.row.roomIsShop">{{item.dictLabel}}</template>
          </template>
        </el-table-column>
        <el-table-column label="是否商品房" align="center" prop="roomSCommercialHouse">
          <template slot-scope="scope">
            <template v-for="item in dictYesNo" v-if="item.dictValue ==scope.row.roomSCommercialHouse">{{item.dictLabel}}</template>
          </template>
        </el-table-column>
        <el-table-column label="房屋户型" align="center" prop="roomHouseType">
          <template slot-scope="scope">
            <template v-for="item in dictRoomHouseType" v-if="item.dictValue ==scope.row.roomHouseType">{{item.dictLabel}}</template>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="160">
          <template slot-scope="scope">
            <span>{{ (scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark"></el-table-column>
        <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            width="200">
          <template slot-scope="scope">
            <el-button
                type="text"
                icon="el-icon-edit"
                @click="onUpdateRoom(scope.row)">修改
            </el-button>
            <el-button
                type="text"
                icon="el-icon-delete"
                @click="tips(scope.row.roomId)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--    分页-->
      <div class="block">
        <!--       触发事件 handleSizeChange表示方法-->
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="current"
            :page-sizes="[5, 10, 20, 30]"
            :page-size="size"
            layout="sizes, prev, pager, next"
            :total="total">
        </el-pagination>
      </div>
      <!--    添加或修改的对话框-->
      <el-dialog :title="title" :visible.sync="dialogFormVisible">
        <el-form :model="room" :rules="rules">
            <el-form-item label="楼栋/单元" placeholder="请选择" :label-width="formLabelWidth">
                <el-cascader
                    style="float: left"
                    v-model="room.unitId"
                    :options="roomTree"
                    clearable
                    @change="handleUnitAndBuilding"></el-cascader>
            </el-form-item>
            <el-form-item label="楼层" :label-width="formLabelWidth" prop="roomLevel">
              <el-input v-model="room.roomLevel" autocomplete="off" placeholder="请输入楼层"></el-input>
            </el-form-item>
            <el-form-item label="房间名称" :label-width="formLabelWidth" prop="roomName">
              <el-input v-model="room.roomName" autocomplete="off" placeholder="请输入房间名称"></el-input>
            </el-form-item>
            <el-form-item label="建筑面积" :label-width="formLabelWidth" prop="roomAcreage">
              <el-input v-model="room.roomAcreage" autocomplete="off" placeholder="请输入建筑面积"></el-input>
            </el-form-item>
            <el-form-item label="算费系数" :label-width="formLabelWidth" prop="roomCost">
              <el-input v-model="room.roomCost" autocomplete="off" placeholder="请输入算费系数"></el-input>
            </el-form-item>
            <el-form-item label="房屋状态" :label-width="formLabelWidth" prop="roomStatus">
              <el-select v-model="room.roomStatus" clearable placeholder="请选择" style="float: left">
                <el-option
                    v-for="item in dictStatus"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否商铺" :label-width="formLabelWidth" placeholder="请选择" prop="roomIsShop">
              <el-radio v-model="room.roomIsShop" label='Y'>是</el-radio>
              <el-radio v-model="room.roomIsShop" label='N'>否</el-radio>
            </el-form-item>
            <el-form-item label="是否商品房" :label-width="formLabelWidth" placeholder="请选择" prop="roomSCommercialHouse">
              <el-radio v-model="room.roomSCommercialHouse" label="Y">是</el-radio>
              <el-radio v-model="room.roomSCommercialHouse" label="N">否</el-radio>
            </el-form-item>
            <el-form-item label="房屋户型" :label-width="formLabelWidth" prop="roomHouseType">
              <el-select v-model="room.roomHouseType" clearable placeholder="请选择" style="float: left">
                <el-option
                    v-for="item in dictRoomHouseType"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue">
                </el-option>
              </el-select>
            </el-form-item>
          <el-row>
            <el-form-item label="备注" :label-width="formLabelWidth">
              <el-input
                  type="textarea"
                  :rows="2"
                  placeholder="请输入内容"
                  v-model="room.remark">
              </el-input>
            </el-form-item>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveRoom">确 定</el-button>
        </div>
      </el-dialog>
    </el-row>
  </div>
</template>

<script>
import FileSaver from "file-saver";
import * as XLSX from "xlsx";

export default {
  name: "ZyRoomView",
  data() {
    return {
      //小区id
      communityId: "",
      //楼栋id
      buildingId: "",
      //单元id
      unitId: "",
      //楼层
      roomLevel: "",
      //房间编号
      roomCode: "",
      //房间名称
      roomName: "",
      //房屋建筑面积
      roomAcreage: "",
      //算费系数
      roomCost: "",
      //房屋状态
      roomStatus: "",
      //是否商铺
      roomIsShop: "",
      //是否商品房
      roomSCommercialHouse: "",
      //房屋户型
      roomHouseType: "",
      //创建时间
      createTime: "",
      //备注
      remark: "",
      //房屋对象集合
      rooms: null,
      // 房屋状态和字典联动
      dictStatus:"",
      //是否  的和字典联动
      dictYesNo:"",
      //房屋户型和字典联动
      dictRoomHouseType:"",
      roomTree:[],
      BuildingList:"",
      // 分页数据
      total: 0,
      current: 1,
      size: 5,
      single: true,  // 非单个禁用
      multiple: true,  // 非多个禁用
      //对话框名称
      title: "",
      //批量删除集合id
      ids:[],
      //添加的弹出框
      dialogFormVisible: false,
      //修改的弹出框
      formLabelWidth: "90px",//form表单输入框的宽度
      //搜索框默认显示
      topInputShow:true,
      //选中的单元楼栋信息
      selectedAreaInfo: [],
      //添加绑定的参数对象
      room: {
        roomId:0,
        communityId: "",
        //楼栋id
        buildingId: "",
        //单元id
        unitId: "",
        //楼层
        roomLevel: "",
        //房间编号
        roomCode: "",
        //房间名称
        roomName: "",
        //房屋建筑面积
        roomAcreage: "",
        //算费系数
        roomCost: "",
        //房屋状态
        roomStatus: "",
        //是否商铺
        roomIsShop: "",
        //是否商品房
        roomSCommercialHouse: "",
        //房屋户型
        roomHouseType: "",
        //创建时间
        createTime: "",
        //备注
        remark: "",
      },
      // //单元/楼栋级联选择器
      // unitAndBuilding: {
      //   value:"buildingId",
      //   label: "buildingName",
      //   children: 'children',
      // },
      //表单验证
      rules: {
        unitId: [
          {required: true, message: '楼栋/单元不能为空', trigger: 'blur'}
        ],
        roomName: [
          {required: true, message: '房间名称不能为空', trigger: 'blur'}
        ],
        roomLevel: [
          {required: true, message: "楼层不能为空", trigger: "blur"},
          {pattern: /^[1-9]\d*$/, message: '请输入正确的整数格式', trigger: "change"}
        ],
        roomHouseType: [
          {required: true, message: "房屋户型不能为空", trigger: "blur"}
        ],
        roomIsShop: [
          {required: true, message: "是否商品不能为空", trigger: "blur"}
        ],
        roomSCommercialHouse: [
          {required: true, message: "是否商品房不能为空", trigger: "blur"}
        ],
        roomStatus: [
          {required: true, message: "房屋不能为空", trigger: "blur"}
        ],
        roomAcreage: [
          {required: true, message: '面积不能为空', trigger: 'blur'},
          {
            pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: '请输入正确格式,可保留两位小数',
            trigger: "change"
          }
        ],
      },
      currentZyCommunityId:'',

    }
  },
  methods: {
    // 房屋集合列表
    loadRoomList(current) {
      this.axios.get("/roomList?current=" + this.current + "&size=" + this.size + "&unitId=" + this.unitId + "&buildingId=" + this.buildingId
          + "&roomStatus=" + this.roomStatus +"&communityId=" + this.currentZyCommunityId)
          .then(res => {
            if (res.data.code == 200) {
              this.total = res.data.data.total
              this.pages = res.data.data.pages
              this.rooms = res.data.data.records
            }
          })
    },


    /** 分页事件**/
    handleSizeChange(val) {
      this.size = val;
      this.loadRoomList(this.current)
    },
    handleCurrentChange(val) {
      this.current = val;
      this.loadRoomList(this.current)
    },
    // 显示单元/楼栋级联选择器内数据
    loaderOptions(){
      this.axios.get("children")
          .then(res => {
            console.log(res.data.data)
            this.BuildingList = res.data.data;
            console.log(this.BuildingList)
            this.BuildingList.forEach(item =>{
              this.roomTree.push({
                value:item.buildingId,
                label:item.buildingName,
                children: item.children.map(item =>({
                  ...item,
                      value: item.unitId,
                      label: item.unitName
                }))
              })
            })
          })
    },
    //单元/楼栋点击事件
    handleUnitAndBuilding(datag) {
      this.room.buildingId=datag[0]
      this.room.unitId =datag[1]
    },
    selectUnitAndBuilding(datag) {
      this.buildingId=datag[0]
      this.unitId =datag[1]
    },
    //复选框的选择、选择一个时修改和删除按钮都显示 、 选择两个的时候只显示删除
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.roomId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    //新增的弹窗
    onRoomAdd() {
      this.empty()
      this.room.roomId= 0
      this.dialogFormVisible = true
      this.title = "添加房间"

    },
    //修改的弹窗
    onUpdateRoom(row) {
      this.room = JSON.parse(JSON.stringify(row))
      this.dialogFormVisible = true
      this.title = "修改房间"

    },
    //添加和修改
    saveRoom(){
      if(this.room.roomId == 0){
        this.room.communityId = this.currentZyCommunityId;
        this.axios.post("/roomSave",this.room)
            .then(res =>{
              if(res.data.code ==200){
                this.loadRoomList(this.current);
                this.dialogFormVisible = false
              }
              this.$message({
                type: 'success',
                message: '添加成功！'
              })
            })
      }else {
        console.log(this.room)
        this.axios.put("/roomUpdate",this.room)
            .then(res =>{
              if (res.data.code == 200){
                this.loadRoomList(this.current);
                this.dialogFormVisible = false
              }
              this.$message({
                type: 'success',
                message: '修改成功！'
              })
            })
      }
    },
    // 删除
    deleteRooms(id) {
      this.axios.delete("roomDelete/" + id)
          .then(res => {
            if (res.data.code == 200) {
              this.loadRoomList(this.current);
            }
          })
    },
    //删除的判断
    tips(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!',
        });
        // this.deleteRole(id);
        this.deleteRooms(id)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //房屋信息和字典联动
    LinkeageRoom(){
      let typeName = "zy_room_state";
      let typeName2 = "sys_yes_no";
      let typeName3 = "zy_house_state";
      this.axios.get("/sysDictData/getBySysDictTypeName/" + typeName)
          .then(res =>{
            this.dictStatus = res.data.data;
          })
      //和字典联动系统是否
      this.axios.get("/sysDictData/getBySysDictTypeName/" + typeName2)
          .then(res =>{
            this.dictYesNo = res.data.data;
          })

      //房屋户型和字典联动
      this.axios.get("/sysDictData/getBySysDictTypeName/" + typeName3)
          .then(res =>{
            this.dictRoomHouseType = res.data.data;
          })
    },

    /** 导出**/
    outExport() {
      this.$confirm("此操作将导出excel文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
          .then(() => {
            this.excelData = this.sysUsers; //你要导出的数据list。
            this.exportExcel();
          })
          .catch(() => {
          });
    },
    exportExcel() {
      //转换成excel时，使用原始的格式
      var xlsxParam = {raw: true};
      let fix = document.querySelector(".el-table__fixed");
      let wb;
      //判断有无fixed定位，如果有的话去掉，后面再加上，不然数据会重复
      if (fix) {
        wb = XLSX.utils.table_to_book(
            document.querySelector("#userData").removeChild(fix), xlsxParam);
        document.querySelector("#userData").appendChild(fix);
      } else {
        wb = XLSX.utils.table_to_book(document.querySelector("#userData"), xlsxParam);
      }
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(new Blob([wbout], {type: "application/octet-stream"}), "导出详情单.xlsx");
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },

    reset() {
      this.roomStatus = "",
          this.$router.go(0);
    },
    //隐藏搜索框
    topInputShows() {
      this.topInputShow = !this.topInputShow;
    },
    //刷新
    refresh(){
      this.$router.go(0)
    },
    empty: function () {
      this.room = {
        roomId: "",
        communityId: "",
        //楼栋id
        buildingId: "",
        //单元id
        unitId: "",
        //楼层
        roomLevel: "",
        //房间编号
        roomCode: "",
        //房间名称
        roomName: "",
        //房屋建筑面积
        roomAcreage: "",
        //算费系数
        roomCost: "",
        //房屋状态
        roomStatus: "",
        //是否商铺
        roomIsShop: "",
        //是否商品房
        roomSCommercialHouse: "",
        //房屋户型
        roomHouseType: "",
        //创建时间
        createTime: "",
        //备注
        remark: "",
      }
    },
    // 联动
    setCurrentZyCommunity(id){
      this.currentZyCommunityId=id
      this.loadRoomList(1)
    },
    //批量删除
    deleteRoomIds(){
      this.axios.delete("room/"+this.ids)
          .then(res =>{
            if(res.data.code == 200){
              this.loadRoomList(this.current)
            }
          })
    },
    //批量删除的判断
    BatchTips(id, delFlagId) {
      this.delFlagId = delFlagId;
      this.id = id;
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!',
        });
        this.deleteRoomIds()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },


  },
  mounted() {
    this.loadRoomList();
    this.LinkeageRoom();
    this.loaderOptions();
    // 联动
    this.$bus.$on('mainCurrentCommunityChange',(id)=>{
      this.setCurrentZyCommunity(id)
    });

  },

}
</script>

<style scoped>

</style>